--
--    Health Organizer (http://sourceforge.net/projects/hor/,
--                      http://hor.sourceforge.net/)
--    Copyright (C) 2015-2017  Andrea Urbani ( matfanjol@users.sf.net )
--
--    This program is free software: you can redistribute it and/or modify
--    it under the terms of the GNU General Public License as published by
--    the Free Software Foundation, either version 3 of the License, or
--    (at your option) any later version.
--
--    This program is distributed in the hope that it will be useful,
--    but WITHOUT ANY WARRANTY; without even the implied warranty of
--    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
--    GNU General Public License for more details.
--
--    You should have received a copy of the GNU General Public License
--    along with this program.  If not, see <http://www.gnu.org/licenses/>.
--
SET statement_timeout = 0;
SET lock_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SET check_function_bodies = false;
SET client_min_messages = warning;
-- ----------
-- Removed the 
-- 'E ' = empty stomach
-- 'F ' = full stomach
-- '==' = no matter
-- types of "When" field of "tDrugsPrescriptions"
update "tDrugs"
set "ID_DrugPrescription" = null
where "ID_DrugPrescription" in (select "ID" from "tDrugsPrescriptions" where "When" in ('E ','F ','=='));
delete from "tDrugsPrescriptions"
where 
"When" in ('E ','F ','==');
-- --------
-- I have to check in the sources if the tDrugsPrescriptions_DeletedV5
-- is empty or not. If it is, a warning message has to appear
-- --------
ALTER TABLE "tDrugsPrescriptions"
   ALTER COLUMN "WhenTime" TYPE time without time zone;
-- ----
alter table "tDocumentsFiles"
  add column "FileDateTime" timestamp without time zone;
update "tDocumentsFiles"
set "FileDateTime"=localtimestamp;
alter table "tDocumentsFiles"
alter column "FileDateTime" set not null;
CREATE TABLE "tLogs"
(
   "ID" serial NOT NULL, 
   "Date" time without time zone NOT NULL DEFAULT localtimestamp, 
   "ID_Person" integer, 
   "Kind" character(1) NOT NULL, 
   "Message" character varying(50) NOT NULL, 
   "Details" text, 
   "ReferenceKey" integer, 
   "Version" integer NOT NULL DEFAULT 1, 
   CONSTRAINT "pk_tLogs" PRIMARY KEY ("ID"), 
   CONSTRAINT "chk_tLogs_Kind" CHECK ("Kind" in ('I','U','D','S')), 
   CONSTRAINT "fk_tLogs_tPersons" FOREIGN KEY ("ID_Person") REFERENCES "tPersons" ("ID") ON UPDATE CASCADE ON DELETE SET NULL
);
COMMENT ON COLUMN public."tLogs"."ID_Person" IS 'Link to the patient, if applicable';
COMMENT ON COLUMN public."tLogs"."Kind" IS 'Kind of the operation that generates the log:
I = Insertion of new data
U = Update of existing data
D = Delete of existing data
S = Substitution of data
';
COMMENT ON COLUMN "tLogs"."Message" IS 'The log message';
COMMENT ON COLUMN "tLogs"."Details" IS 'Details of the log';
COMMENT ON COLUMN "tLogs"."ReferenceKey" IS 'Reference key (when applicable)';
COMMENT ON COLUMN "tLogs"."Version" IS 'Version of the used logging method';
COMMENT ON TABLE "tLogs"
  IS 'Stores the logs of some operations done by the user';
-- 
ALTER TABLE "tDocumentsFiles"
  ADD "DrugBox" boolean not null default false;
comment on column "tDocumentsFiles"."DrugBox" is 'When true, this document contains the picture of the external box/package that contains a drug';
ALTER TABLE "tDocumentsFiles"
  ADD "DrugPicture" boolean not null default false;
comment on column "tDocumentsFiles"."DrugPicture" is 'When true, this document contains the picture of a drug';
ALTER TABLE "tDocumentsFiles"
  ADD "DrugInstructions" boolean not null default false;
comment on column "tDocumentsFiles"."DrugInstructions" is 'When true, this document contains the picture/document with the instructions/descriptions of a drug';
ALTER TABLE "tDocumentsFiles"
  add constraint "ck_tDocumentsFiles_DrugFlags"
    check (
( not ( "DrugBox" and "DrugPicture" ) ) and
( not ( "DrugBox" and "DrugInstructions" ) ) and
( not ( "DrugInstructions" and "DrugPicture" ) )
);
-- ----
CREATE TABLE "tAgendaDrugs"
(
   "ID" serial NOT NULL, 
   "ID_Patient" integer NOT NULL, 
   "DateTime" time without time zone NOT NULL, 
   "ID_DrugPrescription" integer, 
   "Status" character(1) not null, 
   "ID_Drug" integer not null,
   "Note" text,
   CONSTRAINT "pk_tAgendaDrugs" PRIMARY KEY ("ID"), 
   CONSTRAINT "fk_tAgendaDrugs_tPatients" FOREIGN KEY ("ID_Patient") REFERENCES "tPatients" ("ID_Person") ON UPDATE CASCADE ON DELETE CASCADE, 
   CONSTRAINT "fk_tAgendaDrugs_tDrugsPrescriptions" FOREIGN KEY ("ID_DrugPrescription") REFERENCES "tDrugsPrescriptions" ("ID") ON UPDATE CASCADE ON DELETE CASCADE, 
   CONSTRAINT "fk_tAgendaDrugs_tDrugs" FOREIGN KEY ("ID_Drug") REFERENCES "tDrugs" ("ID") ON UPDATE CASCADE ON DELETE CASCADE,
   CONSTRAINT "ck_tAgendaDrugs_Status" CHECK ("Status" in ('T','K','S') )
);
comment on column "tAgendaDrugs"."Status" is 'T = To take
K = taKen
S = Skipped';
create index "idx_tAgendaDrugs_PatientDate" on "tAgendaDrugs" ("ID_Patient","DateTime");
create index "idx_tAgendaDrugs_PatientDateStatus" on "tAgendaDrugs" ("ID_Patient","DateTime","Status");
CREATE TABLE "tAgendaExaminations"
(
   "ID" serial NOT NULL, 
   "ID_Patient" integer NOT NULL, 
   "DateTime" time without time zone NOT NULL, 
   "ID_ExaminationPeriodical" integer, 
   "Status" character(1) not null, 
   "ID_Examination" integer not null, 
   "Note" text,
   CONSTRAINT "pk_tAgendaExaminations" PRIMARY KEY ("ID"), 
   CONSTRAINT "fk_tAgendaExaminations_tPatients" FOREIGN KEY ("ID_Patient") REFERENCES "tPatients" ("ID_Person") ON UPDATE CASCADE ON DELETE CASCADE, 
   CONSTRAINT "fk_tAgendaExaminations_tExaminationsPeriodical" FOREIGN KEY ("ID_ExaminationPeriodical") REFERENCES "tExaminationsPeriodical" ("ID") ON UPDATE CASCADE ON DELETE CASCADE,
   CONSTRAINT "fk_tAgendaExaminations_tExaminations" FOREIGN KEY ("ID_Examination") REFERENCES "tExaminations" ("ID") ON UPDATE CASCADE ON DELETE CASCADE,
   CONSTRAINT "ck_tAgendaExaminations_Status" CHECK ("Status" in ('B','T','C','D','M'))
);
comment on column "tAgendaExaminations"."Status" is 'B = to Book
T = booked: To do
C = Cancelled
D = Done
M = Moved to another date/Time';
create index "idx_tAgendaExaminations_PatientDate" on "tAgendaExaminations" ("ID_Patient","DateTime");
create index "idx_tAgendaExaminations_PatientDateStatus" on "tAgendaExaminations" ("ID_Patient","DateTime","Status");
CREATE TABLE "tAgendaCategories"
(
   "ID" serial NOT NULL, 
   "Name" varchar(45) not null,
   "Picture" bytea,
   CONSTRAINT "pk_tAgendaCategories" PRIMARY KEY ("ID")
);
CREATE TABLE "tAgendaFree"
(
   "ID" serial NOT NULL, 
   "ID_Patient" integer NOT NULL, 
   "DateTime" time without time zone NOT NULL, 
   "ID_AgendaCategory" integer not null,
   "Title" varchar(45) not null,
   "Note" text,
   CONSTRAINT "pk_tAgendaFree" PRIMARY KEY ("ID"), 
   CONSTRAINT "fk_tAgendaFree_tPatients" FOREIGN KEY ("ID_Patient") REFERENCES "tPatients" ("ID_Person") ON UPDATE CASCADE ON DELETE CASCADE, 
   CONSTRAINT "fk_tAgendaFree_tAgendaCategories" FOREIGN KEY ("ID_AgendaCategory") REFERENCES "tAgendaCategories" ("ID") ON UPDATE CASCADE ON DELETE CASCADE
);
create index "idx_tAgendaFree_PatientDate" on "tAgendaFree" ("ID_Patient","DateTime");
CREATE TABLE "tProsthesisCompanies"
(
  "ID" serial NOT NULL,
  "Name" character varying(45) NOT NULL,
  "Note" text,
  "Expired" boolean NOT NULL DEFAULT false,
  "Origin" character varying(15),
  CONSTRAINT "pk_tProthesisCompanies" PRIMARY KEY ("ID"),
  constraint "uk_tProthesisCompanies_Name" unique ("Name")
);
create table "tProsthesisTypes" (
	"ID" serial not null,
	"Type" char(1) not null,
	"ID_ProsthesisCompany" integer,
	"Model" character varying(45),
	"ID_Document" integer,
	"Note" text,
	"Origin" character varying(15),
	constraint "pk_tProsthesisTypes" primary key ("ID"),
	constraint "fk_tProsthesisTypes_tProsthesisCompanies" foreign key ("ID_ProsthesisCompany") references "tProsthesisCompanies" ("ID") on update cascade on delete cascade,
	constraint "fk_tProsthesisTypes_tDocuments" foreign key ("ID_Document") references "tDocuments" ("ID") on update cascade on delete restrict,
	constraint "uk_tProthesisTypes_CompanyModel" unique ("ID_ProsthesisCompany","Model")
);
create table "tProsthesisTypesAvoidExaminationsNames" (
	"ID_ProsthesisType" integer not null,
	"ID_ExaminationName" integer not null,
	"Note" text,
	constraint "pk_tProsthesisTypesAvoidExaminationsNames" primary key ("ID_ProsthesisType","ID_ExaminationName"),
	constraint "fk_tProsthesisTypesAvoidExaminationsNames_tProsthesisTypes" foreign key ("ID_ProsthesisType") references "tProsthesisTypes" ("ID") on update cascade on delete restrict,
	constraint "fk_tProsthesisTypesAvoidExaminationsNames_tExaminationsNames" foreign key ("ID_ExaminationName") references "tExaminationsNames" ("ID") on update cascade on delete restrict
);
create table "tProsthesis" (
	"ID" serial not null,
	"ID_Patient" integer not null,
	"ID_ProsthesisType" integer not null,
	"Date" timestamp without time zone,
	"SerialNumber" character varying(45),
	"ID_Hospitalization" integer,
	"Place" character varying(45),
	"Removed_Date" timestamp without time zone,
	"Removed_ID_Hospitalization" integer,
	"Note" text,
	constraint "pk_tProsthesis" primary key ("ID"),
	constraint "fk_tProsthesis_tPatients" foreign key ("ID_Patient") references "tPatients" ("ID_Person") on update cascade on delete cascade,
	constraint "fk_tProsthesis_tProsthesisTypes" foreign key ("ID_ProsthesisType") references "tProsthesisTypes" ("ID") on update cascade on delete restrict,
	constraint "fk_tProsthesis_tHospitalizations" foreign key ("ID_Hospitalization") references "tHospitalizations" ("ID") on update cascade on delete restrict,
	constraint "fk_tProsthesis_tHospitalizations_Removed" foreign key ("Removed_ID_Hospitalization") references "tHospitalizations" ("ID") on update cascade on delete restrict
);
-- -----
alter table "tSettings" add column
  "Updating" boolean not null default false;
-- ----------
update "tSettings"
set "DbVersion"=5
where "ID"=1;
